package com.aiton.bamin.bamindaijiadrier.server;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.utils.Arith;
import com.aiton.administrator.shane_library.shane.utils.GsonUtils;
import com.aiton.bamin.bamindaijiadrier.TTSController;
import com.aiton.bamin.bamindaijiadrier.activity.ZjbBaseActivity;
import com.aiton.bamin.bamindaijiadrier.constant.Constant;
import com.aiton.bamin.bamindaijiadrier.customview.OrderToast;
import com.aiton.bamin.bamindaijiadrier.model.SendOrder;
import com.aiton.bamin.bamindaijiadrier.model.User;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.nearby.NearbySearch;
import com.amap.api.services.nearby.NearbySearchResult;
import com.amap.api.services.nearby.UploadInfo;
import com.igexin.sdk.PushManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import cz.msebera.android.httpclient.Header;

public class LocationService extends Service {

    //声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;
    //声明mLocationOption对象
    public AMapLocationClientOption mLocationOption = null;
    public static LatLng mLocationLatLng;
    private boolean isShouFaChe = false;
    private NearbySearch mSearch;
    private TTSController ttsManager;
    private List<SendOrder> mSendOrderList = new ArrayList<>();
    private int mId;
    private OrderToast mOrderToast;
    private User mUser;
    private int timeInterval;
    private int orderId;

    private BroadcastReceiver recevier = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.BROADCASTCODE.SEND_ORDER.equals(action) && isShouFaChe) {
                String sendOrderValue = intent.getStringExtra(Constant.INTENT_KEY.SEND_ORDER_VALUE);
                SendOrder sendOrder = GsonUtils.parseJSON(sendOrderValue, SendOrder.class);
                boolean containOrder = isContainOrder(sendOrder);
                if (!containOrder) {
                    mSendOrderList.add(sendOrder);
                    if (mUser != null) {
                        ttsManager.stopSpeaking();
                        ttsManager.startSpeaking();
                        ttsManager.playText(sendOrder.getStartLocation() + "到"
                                + sendOrder.getEndLocation() + "," + sendOrder.getMileage() + "公里");
                        mOrderToast.show(sendOrder, mUser);
                    }
                } else {
                    Log.e("onReceive ", "onReceive 包含");
                }
            } else if (TextUtils.equals(ZjbBaseActivity.MYBROADCAST, action)) {
                ttsManager.stopSpeaking();
                ttsManager.startSpeaking();
                ttsManager.playText("乘客已取消订单。");
            }
        }
    };
    private boolean mIsUploadLocation;

    /**
     * 判断是否已经收到过该订单
     *
     * @param sendOrder
     */
    private boolean isContainOrder(SendOrder sendOrder) {
        for (int i = 0; i < mSendOrderList.size(); i++) {
            if (TextUtils.equals(sendOrder.getOrderId(), mSendOrderList.get(i).getOrderId())) {
                return true;
            }
        }
        return false;
    }

    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {

        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度
                    //设置上车地址
                    mLocationLatLng = new LatLng(latitude, longitude);
                    if (isShouFaChe) {
                        initNear();
                    }
                    timeInterval++;

                    if (timeInterval == 6) {
                        timeInterval = 0;
                        if (mIsUploadLocation) {
                            pushLocation();
                        }
                    }
                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }

    };

    /**
     * 上传司机坐标
     */
    private void pushLocation() {
        Log.e("LocationService", "坐标: --->>" + mLocationLatLng.longitude + "," + mLocationLatLng.latitude);
        Log.e("LocationService", "id: --->>" + orderId);

        String url = Constant.Url.SEND_COORDINATE;
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("coordinate",  mLocationLatLng.longitude + "," + mLocationLatLng.latitude);
        params.put("id",orderId );
        asyncHttpClient.post(url, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String s = new String(responseBody);
                Log.e("LocationService", "上传司机坐标: --->>" + s);
                try {

                } catch (Exception e) {

                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                Log.e("LocationService", "坐标上传失败: --->>"  );

            }
        });

    }

    private PushManager mPushManager;

    @Override
    public void onCreate() {
        super.onCreate();
        mPushManager = PushManager.getInstance();
        initLocation();
        //语音引擎初始化
        initTtsManager();
        mOrderToast = new OrderToast(LocationService.this);
    }

    private void initTtsManager() {
        ttsManager = TTSController.getInstance(this);
        ttsManager.init();
        ttsManager.startSpeaking();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        Log.e("onStart ", "onStart 服务");
        initAcache();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.BROADCASTCODE.SEND_ORDER);
        filter.addAction(ZjbBaseActivity.MYBROADCAST);
        registerReceiver(recevier, filter);
    }

    private void initAcache() {
        ACache aCache = ACache.get(this);
        mUser = (User) aCache.getAsObject(Constant.ACACHE.USER);
        if (mUser != null) {
            mId = mUser.getDatas().getId();
            Log.e("MainActivity", "服务里面获取用户ID" + mId);
        }
    }

    private void initLocation() {
        //初始化附近派单
        mSearch = NearbySearch.getInstance(LocationService.this);
        mSearch.addNearbyListener(new NearbySearch.NearbyListener() {
            @Override
            public void onUserInfoCleared(int i) {
                Log.e("onUserInfoCleared ", "onUserInfoCleared 附近回调司机测试" + i);
            }

            @Override
            public void onNearbyInfoSearched(NearbySearchResult nearbySearchResult, int i) {
                Log.e("onNearbyInfoSearched ", "onNearbyInfoSearched 附近回调司机测试" + i);
            }

            @Override
            public void onNearbyInfoUploaded(int i) {
                Log.e("onNearbyInfoUploaded ", "onNearbyInfoUploaded 附近回调司机测试" + i);
            }
        });

        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(false);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(10000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }

    public LocationService() {
    }

    public class MyBind extends Binder {//Binder实现了IBinder接口

        public void clearLocation() {
            LocationService.this.clearLocation();
        }

        public void startGetOrder() {
            LocationService.this.startGetOrder();
        }

        public boolean isShouFaChe() {
            boolean shouFaChe = LocationService.this.isShouFaChe();
            return shouFaChe;
        }

        public void uploadLocation(int id) {
            LocationService.this.uploadLocation(id);

        }

        public void stopLoadLocation() {
            LocationService.this.stopLoadLocation();
        }


    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBind();
    }

    public boolean isShouFaChe() {
        return isShouFaChe;
    }

    public void startGetOrder() {
        initNear();
        isShouFaChe = true;
    }


    private int mI = 1;
    private int mJ = 1;

    //初始化附近派单并开始上传司机坐标
    private void initNear() {
        //构造上传位置信息
        UploadInfo loadInfo = new UploadInfo();
        //设置上传位置的坐标系支持AMap坐标数据与GPS数据
        loadInfo.setCoordType(NearbySearch.AMAP);
        //设置上传数据位置,位置的获取推荐使用高德定位sdk进行获取
        Random random = new Random();
        while (true) {
            int i = random.nextInt(10) + 1;
            if (i == mI) {

            } else {
                mI = i;
                break;
            }
        }
        while (true) {
            int j = random.nextInt(10) + 1;
            if (j == mJ) {

            } else {
                mJ = j;
                break;
            }
        }
//        Double add = Arith.add(mLocationLatLng.latitude, Arith.mul((double) mI, 0.000001));
        LatLonPoint position = new LatLonPoint(Arith.add(mLocationLatLng.latitude,
                Arith.mul((double) mI, 0.000001)),
                Arith.add(mLocationLatLng.longitude,
                        Arith.mul((double) mJ,
                                0.000001)));
//        LatLonPoint position = new LatLonPoint(add, mLocationLatLng.longitude);
        Log.e("initNear ", "上传司机坐标经纬度随机司机测试" + position.toString());
        loadInfo.setPoint(position);
        //设置上传用户id
        Log.e("initNear ", "initNear 用户ID" + mId);
        loadInfo.setUserID(mId + "");
        //调用异步上传接口
        NearbySearch.getInstance(getApplicationContext())
                .uploadNearbyInfoAsyn(loadInfo);
        boolean pushTurnedOn = mPushManager.isPushTurnedOn(LocationService.this);
        Log.e("initNear ", "initNear 司机个推是否在线司机测试" + pushTurnedOn);
    }

    /**
     * 清除司机位置，停止接单
     */
    private void clearLocation() {
        isShouFaChe = false;
        Log.e("clearLocation ", "清除司机" + mId);
        //获取附近实例，并设置要清楚用户的id
        mSearch.setUserID("" + mId);
        //调用异步清除用户接口
        mSearch.clearUserInfoAsyn();
    }

    public void uploadLocation(int id) {
        mIsUploadLocation = true;
        orderId = id;

    }

    public void stopLoadLocation() {
        mIsUploadLocation = false;
        pushLocation();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();//停止定位
        mLocationClient.onDestroy();//销毁定位客户端。
        //调用销毁功能，在应用的合适生命周期需要销毁附近功能
        NearbySearch.destroy();
        unregisterReceiver(recevier);
    }
}
